package cn.osworks.aos.server;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 * <b>基于Jetty的嵌入式Servlet容器</b>
 * 
 * @author OSWorks-XC
 * @date 2008-06-06
 * @since 1.0
 */
public class AOSServer {

	/**
	 * 监听端口, 缺省为80
	 */
	private int port = 80;

	/**
	 * 应用上下文, 缺省为/(无上下文)
	 */
	private String webContext = "/";

	public AOSServer() {

	}

	/**
	 * 构造Server实例
	 * 
	 * @param pWebContext
	 * @param pPort
	 */
	public AOSServer(String pWebContext, int pPort) {
		setWebContext(pWebContext);
		setPort(pPort);
	}

	public void start() throws Exception {
		final String webRoot = System.getProperty("user.dir") + "/webapp";
		Server server = new Server();
		server.setStopAtShutdown(true);
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setUseDirectBuffers(false);
		connector.setReuseAddress(false);
		connector.setPort(port);
		server.setConnectors(new Connector[] { connector });
		WebAppContext context = new WebAppContext();
		context.setResourceBase(webRoot);
		context.setContextPath(webContext);
		context.setParentLoaderPriority(true);
		context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
				".*/.*jsp-api-[^/]*\\.jar$|.*/.*jsp-[^/]*\\.jar$|.*/.*taglibs[^/]*\\.jar$|.*/.*jstl[^/]*\\.jar$");
		server.setHandler(context);
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public int getPort() {
		return port;
	}

	/**
	 * 监听端口, 缺省为80
	 * 
	 * @param port
	 */
	public void setPort(int port) {
		this.port = port;
	}

	public String getWebContext() {
		return webContext;
	}

	/**
	 * 应用上下文, 缺省为/(无上下文)
	 * 
	 * @param webContext
	 */
	public void setWebContext(String webContext) {
		this.webContext = webContext;
	}

}
